/****************************************************
          File Name:drop-raise-remove_privilege.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Thu 04 Sep 2014 04:13:57 PM CST
*****************************************************/
/*
 * 比较setuid.c
 * 会发现其错误检查有问题
 * 丢掉和获取特权有问题
 *
 * 而本程序正常,以下分别是angel和set-user-id-root以及root
 * 执行的情况
 * angel:
  ruid: 1000, euid: 1000, suid: 1000
  ruid: 1000, euid: 1000, suid: 1000
  ruid: 1000, euid: 1000, suid: 1000
  ruid: 1000, euid: 1000, suid: 1000

 *set-user-id-root:
  ruid: 1000, euid: 0, suid: 0
  ruid: 1000, euid: 1000, suid: 0
  ruid: 1000, euid: 0, suid: 0
  ruid: 1000, euid: 1000, suid: 1000
  
 *root:
  ruid: 0, euid: 0, suid: 0
  ruid: 0, euid: 0, suid: 0
  ruid: 0, euid: 0, suid: 0
  ruid: 0, euid: 0, suid: 0
 */ 

#include<stdio.h>
#include<sys/types.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/acct.h>
#define _GNU_SOURCE

void myac(void)
{
    acct(NULL);
    if(errno)
    {
        perror("acct");
        printf("\e[35m:( :( :( :( :( :(\e[0m\n");
        //exit(1);
    }
    else
        printf("\e[32m OK \e[0m\n");
}

int main()
{
    uid_t ruid,euid,suid, orieuid;

    orieuid=geteuid();

    getresuid(&ruid,&euid,&suid);
    printf("ruid: %d, euid: %d, suid: %d\n",ruid,euid,suid);

    printf("************* start operating ***********\n");

    seteuid(getuid());

    getresuid(&ruid,&euid,&suid);
    printf("ruid: %d, euid: %d, suid: %d\n",ruid,euid,suid);

    myac();

    seteuid(orieuid);

    getresuid(&ruid,&euid,&suid);
    printf("ruid: %d, euid: %d, suid: %d\n",ruid,euid,suid);

    myac();

    setuid(getuid());

    getresuid(&ruid,&euid,&suid);
    printf("ruid: %d, euid: %d, suid: %d\n",ruid,euid,suid);

    myac();

    return 0;
}
